package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author 86150
 * @description 针对表【teachplan_media】的数据库操作Service实现
 * @createDate 2023-07-11 20:26:12
 */
@Service
public class TeachplanMediaServiceImpl extends ServiceImpl<TeachplanMediaMapper, TeachplanMedia>
        implements TeachplanMediaService {

    @Resource
    private TeachplanMediaMapper teachplanMediaMapper;

    @Resource
    private TeachplanMapper teachplanMapper;

    @Override
    @Transactional
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {

        String mediaId = bindTeachplanMediaDto.getMediaId();
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();

        // 获取课程计划
        Teachplan teachplan = teachplanMapper.selectById(mediaId);
        Integer grade = teachplan.getGrade();
        if (grade != 2) {
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        // 获取课程id
        Long courseId = teachplan.getCourseId();

        // 拼装查询条件
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachplanId);

        // 先删除原有记录
        teachplanMediaMapper.delete(queryWrapper);

        // 添加新纪录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setMediaId(mediaId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());

        int insert = teachplanMediaMapper.insert(teachplanMedia);
        if (insert<=0) {
            XueChengPlusException.cast("添加媒资文件失败");
        }

    }

    @Override
    @Transactional
    public void deleteMedia(Long teachPlanId, String mediaId) {

        // 拼装查询条件
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId)
                .eq(TeachplanMedia::getMediaId,mediaId);

        int delete = teachplanMediaMapper.delete(queryWrapper);
        if (delete<=0){
            XueChengPlusException.cast("删除媒资文件失败");
        }
    }

}




